package com.jsbb.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.jsbb.common.Message;
import com.jsbb.common.enums.HttpCodeEnum;
import com.jsbb.util.LoggerUtils;
import com.jsbb.util.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

/**
 * 权限拦截器
 *
 * @author jsbb
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        Long userId = TokenUtils.getUserId(request);
        LoggerUtils.info("uri={},userId={}", uri, userId);
        if (userId == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(JSON.toJSONString(Message.message(HttpCodeEnum.TOKEN_INVALID)));
            pw.flush();
            pw.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {

    }
}
